package com.test.ssm.article.controller;

import com.test.ssm.article.entity.pojo.ArticleType;
import com.test.ssm.article.entity.pojo.SystemUser;
import com.test.ssm.article.entity.vo.SystemFunctionItem;
import com.test.ssm.article.service.SystemFunctionService;
import com.test.ssm.article.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/user")
public class SystemUserController {

    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private SystemFunctionService systemFunctionService;

    @PostMapping("/login")
    public String login(SystemUser systemUser, HttpSession session, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException {
        SystemUser user = systemUserService.login(systemUser);
        if(user != null){
            List<SystemFunctionItem> functions = systemFunctionService.getAllSystemFunctionByRoleId(user.getRoleId());
            System.out.println("functions.size() = " + functions.size());
            session.setAttribute("functions",functions);
            session.setAttribute("user",user);
            return "main/main";
        }else {
            //中文
            redirectAttributes.addAttribute("msg","用户名或密码错误");
            return "redirect:/index.jsp";
//            return "redirect:/index.jsp?msg=" + URLEncoder.encode("用户名或密码错误","utf-8");
        }
    }

    @GetMapping("/login_out")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "redirect:/index.jsp";
    }

    @GetMapping("/to_main")
    public String toMain(){
        return "main/main";
    }
}
